import axios from 'axios'
import { ElMessage } from 'element-plus'
import { getToken } from '@/utils/auth'
import store from '@/store'
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API
})

service.interceptors.request.use(
  (config) => {
    if (getToken()) {
      const token = getToken()
      const userId = store.state.app.user.id
      config.headers.Authorization = token + userId
    }
    return config
  },
  (error) => {
    return Promise.reject(new Error(error))
  }
)

service.interceptors.response.use(
  (response) => {
    const data = response.data
    if (data.success) {
      return data
    } else if (response.status === 200 && data.success === false) {
      ElMessage.error(data.message)
    } else if (response.status === 200) {
      return response
    } else {
      ElMessage.error(data.message)
      return Promise.reject(new Error(data.message))
    }
  },
  (error) => {
    // 请求状态码不是 200 的情况，会走这里
    if (error.response.status === 401) {
      store.dispatch('app/logout')
      // 提示用户
      ElMessage.error('登录过期，清重新登录')
    } else {
      // 统一错误提示
      error.response && ElMessage.error(error.response.data)
    }
    console.log(error.response)

    return Promise.reject(new Error(error.response.data))
  }
)
export default service
